<template>
  <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
    <el-form-item label="用户名：" prop="name">
      {{ user.username }}
    </el-form-item>
    <el-form-item label="原密码：" prop="pwd">
      <el-input v-model="form.pwd" placeholder="请输入原密码" show-password></el-input>
    </el-form-item>
    <el-form-item label="新密码：" prop="newpwd">
      <el-input v-model="form.newpwd" placeholder="请输入新密码" show-password></el-input>
    </el-form-item>
    <el-form-item label="重复新密码：" prop="newpwd2">
      <el-input v-model="form.newpwd2" placeholder="请输入重复新密码" show-password></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import type {LayerType} from '@/components/layer/index.vue'
import type {Ref} from 'vue'
import type {ElFormItemContext} from 'element-plus/lib/el-form/src/token'
import {ref} from 'vue'
import store from "@/store"
import {ElMessage} from 'element-plus'
import {passwordChange} from '@/api/user'

const ruleForm: Ref<ElFormItemContext | null> = ref(null)
const layerDom: Ref<LayerType | null> = ref(null)
let user: any = store.state.user.info

let form = ref({
  name: '',
  pwd: '',
  newpwd: '',
  newpwd2: ''
})
const rules = {
  pwd: [{required: true, message: '请输入原密码', trigger: 'blur'}],
  newpwd: [{required: true, message: '请输入新密码', trigger: 'blur'}],
  newpwd2: [{required: true, message: '请输入重复新密码', trigger: 'blur'}],
}

function onSubmit() {
  if (ruleForm.value) {
    ruleForm.value.validate((valid) => {
      if (valid) {
        let params = {
          ...form.value
        }
        passwordChange(params)
            .then(res => {
              ElMessage({
                type: 'success',
                message: '密码修改成功，即将跳转到登录页面'
              })
              layerDom.value && layerDom.value.close()
              setTimeout(() => {
                store.dispatch('user/loginOut')
              }, 2000)
            })
      } else {
        return false;
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.layout-container {
  width: calc(100% - 10px);
  height: 100%;
  margin: 0 0 0 10px;
}
</style>